var db;
var dbCreated = false;

// connect to database
function connectDBLesson() {
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",
			500000);
	db.transaction(getLessonList, errorCB);
}

// function will be called when an error occurred
function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

function successCB() {
	dbCreated = true;
	db.transaction(getLessonList, errorCB);
}

function getLessonList(tx) {
	var sql = "SELECT le_id,le_title, le_dataversion_id  " + " From lesson "
			+ " ORDER BY le_id ASC ";
	tx.executeSql(sql, [], showLessonList);
}


function getLessonTitle(id) {
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",
			500000);
	
	var title = '';
	var def = $.Deferred();
	db.transaction(function(tx) {
		tx.executeSql('SELECT le_title FROM lesson WHERE le_id =? ;', [ id ],
				function(tx, result) {
					title += result.rows.item(0).le_title;
					def.resolve(title);
				}, errorCB);
	}, errorCB);
	return def.promise();
}


// ok
function showLessonList(tx, results) {
	// test();
	var len = results.rows.length;
	for (var i = 0; i < len; i++) {
		var data = results.rows.item(i);
		$('#lesson-list')
				.append(
						'<li><a data-ajax="false" href="?leid='
								+ data.le_id
								+ '" data-rel="close" class="ui-btn ui-btn-icon-right ui-icon-carat-r">'
								+ data.le_title + '</a></li>');
	}
}


function selectLessonList(){
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(function(tx){
		var sql = "SELECT le_id, le_title FROM lesson WHERE le_id ORDER BY le_id ASC";
		tx.executeSql(sql, [], function(tx, results) {
			var len = results.rows.length;
			
			for (var i = 0; i < len; i++) {
				$('#select-lesson-list').append('<option value="'+results.rows.item(i).le_id+'">'+results.rows.item(i).le_title+'</option>');
	        }
			$('#select-lesson-list').selectmenu('refresh');
			
		/*	for (var i = 0; i < len; i++) {
				if (results.rows.item(i).le_id == 2) {
					$('#select-lesson-list').append('<option selected="selected" value="'+results.rows.item(i).le_id+'">'+results.rows.item(i).le_title+'</option>');
				}else{
					$('#select-lesson-list').append('<option value="'+results.rows.item(i).le_id+'">'+results.rows.item(i).le_title+'</option>');
				}
	        }
			$('#select-lesson-list').selectmenu('refresh');*/
			
			
		});
		
	}, errorCB);
}

